﻿using Sustainalytics.Accounts.BusinessLogic;
using Sustainalytics.Accounts.Service.Models;
using Sustainalytics.AuthOperations;
using Sustainalytics.DataLayer.Exceptions.AccountsAndUsers;
using Sustainalytics.Utils;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace Sustainalytics.Accounts.Service.Controllers
{
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/v1/accounts/{accountId}/users")]
    public class AccountUsersController : ApiController
    {
        private readonly IAccountsManagement _accountsManagement;

        public AccountUsersController(IAccountsManagement accountsManagement, IAuthOperations authOperations)
        {
            _accountsManagement = accountsManagement;
        }

        [Route("")]
        public HttpResponseMessage Get(Guid accountId, [FromUri]ListOptions filters, string status = null)
        {
            try
            {
                var nullableStatus = Enum.TryParse(status, out Entities.Status statusEnum) ? statusEnum : (Entities.Status?)null;

                if (filters != null && filters.GetCount)
                {
                    int usersCount = 0;
                    try
                    {
                        usersCount = _accountsManagement.GetUsersTotalCount(new List<Guid>() { accountId }, nullableStatus, "");
                    }
                    catch (AccountNotFoundException ex)
                    {
                        return Request.CreateResponse(System.Net.HttpStatusCode.NotFound, new { Code = ErrorCodes.ErrorRetrievingUsers });
                    }
                    catch (Exception ex)
                    {
                        return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, new { Code = ErrorCodes.ErrorRetrievingUsers });
                    }

                    return Request.CreateResponse(System.Net.HttpStatusCode.OK, usersCount);
                }

                var response = _accountsManagement.GetUsers(new List<Guid>() { accountId }, nullableStatus, "", filters);
                List<object> accountUsers = new List<object>();
                response.ForEach(u => accountUsers.Add(UserDto.CreateIdFullNameEmailStatus(u)));

                return Request.CreateResponse(System.Net.HttpStatusCode.OK, accountUsers);
            }
            catch (AccountNotFoundException ex)
            {
                return Request.CreateResponse(System.Net.HttpStatusCode.NotFound, new { Code = ErrorCodes.ErrorRetrievingUsers });
            }
            catch (Exception ex)
            {
                return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError, new { Code = ErrorCodes.ErrorRetrievingUsers });
            }
        }
    }
}
